package searchtab.search.textfile;

import java.util.ArrayList;

import org.eclipse.jface.text.IFindReplaceTarget;
import org.eclipse.jface.text.Position;
import org.eclipse.swt.graphics.Point;

import searchtab.search.options.SearchOptions;

public class TextSearcherUtils {

    public static ArrayList<Position> findAll(String text, StringMatcher stringMatcher, int startPosition) {
        Position position;
        ArrayList<Position> result = new ArrayList<Position>();
        while ((position = stringMatcher.find(text, startPosition, text.length())) != null) {
            result.add(position);
            startPosition = position.getOffset() + position.getLength();
        }
        return result;
    }

    public static int findAndSelect(IFindReplaceTarget target, boolean goForward, boolean stepRequired,
            SearchState searchState) {

        if (target == null) {
            return -1;
        }
        Point point = target.getSelection();
        if (point == null) {
            return -1;
        }
        int findReplacePosition = point.x;
        if (goForward) {
            if (stepRequired) {
                findReplacePosition += point.y;
            }
        } else {
            findReplacePosition -= point.y;
        }

        int index = findAndSelect(target, findReplacePosition, goForward, searchState);
        return index;
    }

    public static int findAndSelect(IFindReplaceTarget target, int findReplacePosition, boolean goForward,
            SearchState searchState) {
        int index = target.findAndSelect(findReplacePosition, searchState.getFilterText(), goForward, SearchOptions
                .isMatchCase(), false);

        if (index == -1) {
            index = target
                    .findAndSelect(-1, searchState.getFilterText(), goForward, SearchOptions.isMatchCase(), false);

        }
        return index;
    }
}
